<!--
*  2021-03-15
*  码单详情
-->
<template>
  <div id="app" class="detailed-operate">
    <!-- 头部导航 -->
    <van-nav-bar
      :title="title"
      ref="header"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <van-icon name="scan" size="20" v-permissions="'45_485'" />
      </template>
    </van-nav-bar>

    <!-- 总计 -->
    <van-cell
      class="detailed-operate__total"
      v-show="tableData.length !== 0"
      :title="'总计长度: ' + totalLength"
    >
      <template slot="default">
        <div>
          <span>{{ "总计重量: " + totalWeight }}</span>
          <span>{{ "总计匹数: " + totalNum }}</span>
        </div>
      </template>
    </van-cell>

    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <van-swipe-cell v-for="(data, index) in tableData" :key="index">
          <div
            v-for="(d, key, i) in data"
            :key="i"
            class="detailed-operate__wrapper"
          >
            <van-cell v-if="i === 0" :title="'编号: ' + key">
              <template slot="label">
                <div>
                  <van-cell
                    v-for="(dd, dIndex) in d"
                    :key="dd.id"
                    :title="'长度: ' + dd.length"
                  >
                    <template slot="default">
                      <div>
                        <span> {{ "重量: " + dd.weight }} </span>
                        <van-icon
                          name="delete"
                          v-show="!detailId"
                          @click="onClickDelSingle(index, dIndex, dd.id)"
                        ></van-icon>
                      </div>
                    </template>
                  </van-cell>
                  <van-cell
                    :title="'总长度: ' + data.totalLength"
                    :value="'总重量: ' + data.totalWeight"
                  ></van-cell>
                </div>
              </template>
              <template slot="default">
                <div>
                  <span>{{ "总匹数: " + d.length }}</span>
                </div>
              </template>
            </van-cell>
          </div>
          <template #right>
            <van-button
              square
              type="danger"
              text="删除"
              v-show="!detailId"
              @click="onClickDelAll(index)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        v-show="tableData.length === 0"
        description="暂无数据"
      />
    </better-scroll>

    <van-cell-group class="detailed-operate-btn" v-permissions="'486_489'">
      <van-button
        block
        type="info"
        class="bgColor"
        @click="onClickConfirmNote"
        v-show="confirmFlag != 1"
        >确 认</van-button
      >
    </van-cell-group>

    <van-cell-group class="detailed-operate-btn" v-permissions="'487_488'">
      <van-button
        block
        type="info"
        class="bgColor"
        @click="onClickConfirmReceive"
        v-show="receiveFlag != 1"
        >接 收</van-button
      >
    </van-cell-group>

    <van-cell-group class="detailed-operate-btn" v-permissions="'45_485'">
      <van-button
        block
        type="info"
        class="bgColor"
        v-show="tableData.length !== 0 && !detailId"
        @click="onClickConfirmAdd"
        >保 存</van-button
      >
    </van-cell-group>
  </div>
</template>

<script>
import { openWin } from "@/utils/index";
import { getMacAddress } from "@/utils/auth";
import {
  getClothNoteDetail,
  getClothNoteAdd,
  getClothNoteByTaskId,
  getClothNoteById,
  getClothNoteReceive,
  getClothNoteConfirm,
} from "@/api/yarn";
// import dayjs from 'dayjs'

export default {
  name: "materialDetailedOperate",
  data() {
    return {
      title: "码单详情",
      totalPage: 1,
      resultArr: [],
      tableData: [
        // {
        //   "211900-A-148": [
        //     {
        //       no: "211900",
        //       length: "60.25",
        //       weight: "56.5",
        //       id: 22,
        //     },
        //     {
        //       no: "211900",
        //       length: "59.25",
        //       weight: "56.5",
        //       id: 33,
        //     },
        //   ],
        //   totalLength: 200,
        //   totalWeight: 150,
        // },
        // {
        //   "211900-A-148": [
        //     {
        //       no: "211900",
        //       length: "60.25",
        //       weight: "56.5",
        //       id: 22,
        //     },
        //     {
        //       no: "211900",
        //       length: "59.25",
        //       weight: "56.5",
        //       id: 33,
        //     },
        //   ],
        //   totalLength: 200,
        //   totalWeight: 150,
        // },
        // {
        //   "211900-A-148": [
        //     {
        //       no: "211900",
        //       length: "60.25",
        //       weight: "56.5",
        //       id: 22,
        //     },
        //     {
        //       no: "211900",
        //       length: "59.25",
        //       weight: "56.5",
        //       id: 33,
        //     },
        //   ],
        //   totalLength: 200,
        //   totalWeight: 150,
        // },
        // {
        //   "211900-A-222": [
        //     {
        //       no: "211900",
        //       length: "59.25",
        //       weight: "56.5",
        //       id: 44,
        //     },
        //   ],
        //    totalLength: 59.25,
        //   totalWeight: 56,
        // },
      ],
      detailId: "",
      totalLength: 0,
      totalWeight: 0,
      totalNum: 0,
      confirmFlag: "",
      receiveFlag: "",
      printStatus: "",
    };
  },
  watch: {
    // 监听是编辑还是新增
    detailId(val) {
      if (val) {
        this.onGetClothNoteDetail();
      }
    },
    // 监听码单数组
    tableData: {
      handler(val) {
        this.totalLength = this.countTotal(val, "totalLength");
        this.totalWeight = this.countTotal(val, "totalWeight");
        this.totalNum = this.resultArr.length;
      },
      deep: true,
    },
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      that.detailId = window.api.pageParam ? window.api.pageParam.id : "";
      that.receiveFlag = window.api.pageParam ? window.api.pageParam.receiveFlag : "";
      that.confirmFlag = window.api.pageParam ? window.api.pageParam.confirmFlag : "";
      if (that.detailId == "" && that.receiveFlag == "" && that.confirmFlag == "") {
        that.onClickRight();
      }
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回列表
    onClickLeft() {
      openWin("material-detailed");
    },
    // 扫码
    onClickRight() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let content = ret.result;
          let taskId = "";
          if (that.$validURL(content)) {
            let index = content.indexOf("taskId=");
            let lastIndex = content.indexOf("&craftId=");
            taskId = content.substr(
                index + 7,
                lastIndex == -1 ? content.length - index - 7 : lastIndex - index - 7
            );
            getClothNoteByTaskId(taskId.toString(), (res) => {
              if (that.resultArr.length != 0) {
                let index = that.resultArr.findIndex(
                    (item) => item.id === res.id
                );
                if (index === -1) {
                  if (
                      !res.length ||
                      res.length == 0 ||
                      res.weight == 0 ||
                      !res.weight
                  ) {
                    that.$toast.fail("坯布信息不存在");
                    return false;
                  } else {
                    that.resultArr.push(res);
                  }
                } else {
                  that.$toast.fail("坯布信息已存在");
                  return false;
                }
              } else {
                that.resultArr.push(res);
              }
              that.tableData = that.handlerDatas(that.resultArr);
              that.$toast({
                type: "loading",
                message: "请等待",
                duration: 500,
                onClose: () => {
                  that.onClickRight();
                },
              });
            });
          } else {
            getClothNoteById(content.toString(), (res) => {
              console.log(res, "res");
              if (that.resultArr.length != 0) {
                let index = that.resultArr.findIndex(
                    (item) => item.id === res.id
                );
                if (index === -1) {
                  if (
                      !res.length ||
                      res.length == 0 ||
                      res.weight == 0 ||
                      !res.weight
                  ) {
                    that.$toast.fail("坯布信息不存在");
                    return false;
                  } else {
                    that.resultArr.push(res);
                  }
                } else {
                  that.$toast.fail("坯布信息已存在");
                  return false;
                }
              } else {
                that.resultArr.push(res);
              }
              that.tableData = that.handlerDatas(that.resultArr);
              that.$toast({
                type: "loading",
                message: "请等待",
                duration: 500,
                onClose: () => {
                  that.onClickRight();
                },
              });
            });
          }
        }
      });
    },
    // 详情
    onGetClothNoteDetail() {
      this.tableData = [];
      getClothNoteDetail(this.detailId.toString(), (res) => {
        this.resultArr = res;
        this.tableData = this.handlerDatas(res);
        // alert(JSON.stringify(res))
      });
    },
    // 数据处理
    handlerDatas(arr) {
      let tempArr = [];
      let afterData = [];
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        let key = item.designNo;
        if (tempArr.indexOf(key) === -1) {
          afterData.push({
            [item.designNo]: [item],
            totalLength: item.length,
            totalWeight: item.weight,
          });

          tempArr.push(key);
        } else {
          for (let j = 0; j < afterData.length; j++) {
            for (var designNo in afterData[j]) {
              if (designNo == arr[i].designNo) {
                afterData[j][designNo].push(arr[i]);
                let totalLength =
                  Number(afterData[j].totalLength) + Number(arr[i].length);
                let totalWeight =
                  Number(afterData[j].totalWeight) + Number(arr[i].weight);

                afterData[j].totalLength = !isNaN(parseFloat(totalLength))
                  ? totalLength.toFixed(2)
                  : totalLength;
                afterData[j].totalWeight = !isNaN(parseFloat(totalWeight))
                  ? totalWeight.toFixed(2)
                  : totalWeight;
                break;
              }
            }
          }
        }
      }
      return afterData; // 最终输出
    },
    // 新增码单
    onClickConfirmAdd(res) {
      let details = [];
      console.log(this.tableData);
      this.tableData.forEach((items) => {
        for (let key in items) {
          console.log(items);
          console.log(key);
          console.log(items[key]);
          if (key != "totalLength" && key != "totalWeight") {
            items[key].forEach((item) => {
              details.push({ greyClothId: item.id });
            });
          }
        }
      });

      getClothNoteAdd(
        {
          toDep: "染整车间",
          details: details,
        },
        () => {
          this.$toast({
            type: "success",
            message: "新增码单成功",
            duration: 1000,
            onClose: () => {
              this.resultArr.push(res);
              // openWin('material-detailed')
              // this.printStatus = true
              // this.isEnabledBluetooth()
            },
          });
        }
      );
    },
    // 码单接收
    onClickConfirmReceive() {
      getClothNoteReceive(
        {
          noteId: this.detailId,
        },
        () => {
          this.$toast({
            type: "success",
            message: "接收成功",
            onClose: () => {
              openWin("material-detailed");
            },
          });
        }
      );
    },
    // 码单确认
    onClickConfirmNote() {
      getClothNoteConfirm(
        {
          noteId: this.detailId,
        },
        () => {
          this.$toast({
            type: "success",
            message: "确认成功",
            onClose: () => {
              openWin("material-detailed");
            },
          });
        }
      );
    },
    // 删除单个
    onClickDelSingle(index, dIndex, delId) {
      let delIndex = this.resultArr.findIndex((item) => item.id === delId);
      this.resultArr.splice(delIndex, 1);
      for (let key in this.tableData[index]) {
        console.log(key);
        if (this.tableData[index][key].length === 1) {
          this.tableData.splice(index, 1);
        } else {
          if (key != "totalLength" && key != "totalWeight") {
            let totalLength =
              Number(this.tableData[index].totalLength) -
              Number(this.tableData[index][key][dIndex].length);
            let totalWeight =
              Number(this.tableData[index].totalWeight) -
              Number(this.tableData[index][key][dIndex].weight);
            this.tableData[index].totalLength = !isNaN(parseFloat(totalLength))
              ? totalLength.toFixed(2)
              : totalLength;
            this.tableData[index].totalWeight = !isNaN(parseFloat(totalWeight))
              ? totalWeight.toFixed(2)
              : totalWeight;
            this.tableData[index][key].splice(dIndex, 1);
          }
        }
      }
    },
    // 删除点击所有
    onClickDelAll(index) {
      for (let key in this.tableData[index]) {
        if (key != "totalLength" && key != "totalWeight") {
          this.tableData[index][key].forEach((item) => {
            let index = this.resultArr.findIndex(
              (items) => JSON.stringify(items) === JSON.stringify(item)
            );
            if (index != -1) {
              this.resultArr.splice(index, 1);
            }
          });
        }
      }
      this.tableData.splice(index, 1);
    },
    // 计算总重量/总长度
    countTotal(arr, keyName) {
      let $total = 0;
      $total = arr.reduce(function (total, currentValue) {
        console.log(currentValue[keyName]);
        return currentValue[keyName]
          ? total + Number(currentValue[keyName])
          : Number(total);
      }, 0);
      return $total;
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddress() {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress:  getMacAddress() ? getMacAddress().address : '',
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    that.printLabel();
                  },
                });
              }
            } else if (ret.message === "连接失败") {
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 10,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: "艺多染整",
            },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.$toast.success("打印成功");
            openWin("material-detailed");
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
  },
};
</script>

<style lang="scss">
.detailed-operate {
  .public-scroll {
    height: calc(100vh - 194px);
    overflow: hidden;
    .detailed-operate__wrapper {
      & > .van-cell {
        border-bottom: 1px solid #ddd;
        & > .van-cell__title {
          flex: 0 0 80%;
          .van-cell__label {
            & > div {
              & > .van-cell {
                &:last-child {
                  span {
                    font-size: 14px;
                    font-weight: 800;
                    color: #323233;
                  }
                }
              }
            }
          }
          .van-cell__value {
            div {
              display: flex;
              justify-content: space-between;
              align-items: center;
              .van-icon {
                font-size: 20px !important;
              }
              span {
                &:last-child {
                  margin-left: 20px;
                }
              }
            }
          }
        }
        & > .van-cell__value {
          & > div {
            display: flex;
            flex-direction: column;
          }
        }
      }
    }
    .van-swipe-cell__right {
      .van-button {
        height: 100% !important;
      }
    }

    .detailed-operate-cell {
      display: flex;
      flex-direction: column;
      & > div {
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .detailed-operate__total {
    position: relative;
    z-index: 9999;
    span {
      color: green;
    }
    .van-cell__title {
      flex: 0 0 36%;
    }
    .van-cell__value {
      & > div {
        display: flex;
        justify-content: space-between;
        span {
          display: line-block;
          flex: 1;
          &:first-child {
            text-align: center;
          }
        }
      }
    }
  }
  .detailed-operate-btn {
    height: 110px;
    padding: 16px;
    background: whitesmoke;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>
